package com.muse.app.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.muse.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: lee
 * Date: 2021/4/25
 * Time: 2:28 下午
 * Description:
 */
@Service
@Slf4j
public class FileService {

    private static final int VEDIO_MAX_POST_SIZE = 20 * 1024 * 1024;


    private OSS ossClient;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String ossEndpoint;

    @Value("${ali.accessKey.Id}")
    private String aliAccessKey;

    @Value("${ali.accessKey.secret}")
    private String aliAccessKeySecret;


    @Bean
    public void buildOssClient() {
        ossClient = new OSSClientBuilder().build(ossEndpoint, aliAccessKey, aliAccessKeySecret);
    }


    public Result<Map<String, String>> upload(MultipartFile file, HttpServletRequest request) {
        String contentType = file.getContentType();
        String extension = mimeTypeToExtension(contentType);
        if (StringUtils.isEmpty(extension)) {
            return Result.failure("上传失败,数据格式不支持", null);
        }
        if (ImmutableList.of("video/mp4").contains(contentType) && file.getSize() > VEDIO_MAX_POST_SIZE) {
            return Result.failure("请上传小于20M的视频", null);
        }
        String fileName = UUID.randomUUID().toString() + extension;
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setCacheControl("public, max-age=604800");
            metadata.setContentDisposition("");
            metadata.setContentDisposition("inline;filename=" + fileName);
            ossClient.putObject(bucketName, fileName, file.getInputStream(), metadata);
        } catch (Exception e) {
            log.error("upload file error", e);
            return Result.failure("上传失败", null);
        }
        String url = "https://" + bucketName + "." + ossEndpoint + "/" + fileName;
        return Result.success(ImmutableMap.of("url", url));
    }

    public static String mimeTypeToExtension(String mimeType) {
        if (StringUtils.isEmpty(mimeType)) {
            return "";
        }
        String s = mimeType.toLowerCase();
        String type = s.split(";")[0];
        switch (type) {
            case "image/jpeg":
                return ".jpg";
            case "image/gif":
                return ".gif";
            case "image/png":
                return ".png";
            case "application/pdf":
                return ".pdf";
            case "application/vnd.ms-excel":
                return ".xls";
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                return ".xlsx";
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                return ".docx";
            case "application/msword":
                return ".doc";
            case "video/mp4":
                return ".mp4";
            default:
                log.warn("unknown mime-type,mime-type={}", mimeType);
                return "";
        }
    }
}
